<!-- 物料/产品分类 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true"
    ><template #buts>
      <a-button type="primary" @click="addOrEdit('main')">
        <template #icon> <icon-plus /> </template>新增主分类</a-button
      ></template
    ></pageHeader
  >
  <div class="search-box">
    <a-space :size="30">
      <div style="display: flex">
        <a-space :size="30">
          <a-space>
            <a-input-search
              placeholder="请输入分类名称"
              v-model="searchName"
              @change="search"
              @search="search"
              search-button
            />
          </a-space>
        </a-space>
      </div>

      <div>
        <a-space>
          <!-- <a-button type="primary">
              <template #icon> <icon-search /> </template>搜索</a-button
            > -->
          <a-button type="outline" @click="reset">
            <template #icon> <icon-sync /> </template>重置</a-button
          >
        </a-space>
      </div>
    </a-space>
  </div>

  <tableTurn
    style="padding: 0 10px"
    :tableData="getData"
    ref="tableRef"
    :is-show-pagination="false"
    :args="args"
  >
    <!-- <a-table-column :width="80" align="center">
      <template #title> 序号 </template>
      <template #cell="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
    </a-table-column> -->
    <a-table-column
      :width="150"
      align="center"
      title="分类名称"
      data-index="name"
    >
    </a-table-column>
    <!-- <a-table-column align="center" title="排序" data-index="sort">
        </a-table-column> -->
    <a-table-column
      :width="150"
      align="center"
      title="物料/产品"
      data-index="category"
    >
    </a-table-column>
    <a-table-column :width="150" align="center" title="创建时间">
      <template #cell="{ record }">
        {{ `${dayjs(record.createdAt).format('YYYY-MM-DD hh:mm:ss')}` }}
      </template>
    </a-table-column>
    <a-table-column
      align="center"
      :width="150"
      title="备注"
      data-index="remark"
      :ellipsis="true"
      :tooltip="{
        position: 'top',
      }"
    >
    </a-table-column>
    <a-table-column align="center" :width="150" fixed="right" title="操作">
      <template #cell="{ record }">
        <a-space>
          <a-tooltip content="新增">
            <IconFont
              type="icon-add-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="addOrEdit('child', record)"
            />
          </a-tooltip>
          <a-tooltip content="编辑">
            <IconFont
              type="icon-edit"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="addOrEdit('edit', record)"
            />
          </a-tooltip>
          <a-tooltip content="删除">
            <a-popconfirm
              content="确认删除？"
              type="error"
              @ok="deleteItem(record.id)"
            >
              <IconFont
                type="icon-delete"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </a-space>
      </template>
    </a-table-column>
  </tableTurn>

  <addCatetory
    @categoryEmit="categoryEmit"
    v-model:visible="modalVisible"
    :type="currType"
    :form="currForm.list"
    :fatherName="fatherName"
  ></addCatetory>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import dayjs from 'dayjs';
  import { flatTree } from '@/utils/utils';
  import {
    GetClassificationList,
    PostClassificationList,
    delClassification,
  } from '@/api/inventory-management/material-management';
  import addCatetory from './components/add-catetory/index.vue';

  const title: string = '物料/产品分类';
  const breadCrumb: string[] = ['库存管理', '物料管理', '物料/产品分类'];
  // 表格配置
  const args = reactive({
    stripe: true,
    bordered: {
      headerCell: true,
    },
    rowKey: 'name',
  });
  const searchName = ref();
  let tableRef = ref();
  let fatherName = ref(''); // 储存父级类型

  // 储存扁平化的树状结构
  let flatData: any = [];

  // 获取列表数据
  const getData = async (pageData?: any) => {
    try {
      const data: any = {};
      if (searchName.value) data.name = searchName.value;
      const res = await GetClassificationList({
        ...data,
      });
      flatData = flatTree(res, 'children');

      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };
  let modalVisible = ref(false);
  let currType = ref(''); // 判断是新增主分类还是子分类
  const currForm = reactive({
    list: {},
  });

  // 新增或编辑
  const addOrEdit = (type: string, record?: any) => {
    if (record) {
      if (type === 'child' && record.pid > 0) {
        fatherName.value = record
          ? flatData.find((item: any) => item.id === record.pid).name
          : '';
      } else {
        fatherName.value = record.name;
      }
    }

    currType.value = type;
    currForm.list = record ? record : '';
    modalVisible.value = true;
  };

  // 弹出框的自定义事件
  const categoryEmit = async (form: any, type: string) => {
    try {
      let data: any = {};
      // 新增主类
      if (type === 'main') {
        data.pid = 0;
        data.name = form.name;
        data.category = form.category;
        data.remark = form.remark;
      }
      // 新增子类
      else if (type === 'child') {
        data.pid = form.id;
        data.name = form.name;
        data.category = form.category;
        data.remark = form.remark;
      }
      // 编辑类型
      else {
        data = form;
      }
      await PostClassificationList({
        ...data,
      });
      tableRef.value.loadData();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  // 删除一项
  const deleteItem = async (id: number) => {
    try {
      await delClassification({ id });
      tableRef.value.loadData();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  const search = () => {
    tableRef.value.loadData();
  };

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableRef.value.loadData();
    }
  };

  const reset = () => {
    searchName.value = '';
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  .state-item-Y {
    width: 30px;
    height: 30px;
    font-size: 12px;
    border: 1px solid rgba(148, 191, 255, 1);
    background-color: rgba(232, 243, 255, 1);
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #3d7eff;
  }
  .state-item-N {
    color: #f53f3f;
    width: 30px;
    height: 30px;
    font-size: 12px;
    border: 1px solid rgba(251, 172, 163, 1);
    background-color: rgba(255, 236, 232, 1);
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .search-box {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 10px;
    margin-top: -7px;
  }

  // .space-unit {
  //   background-color: var(--color-bg-2);
  //   border-radius: 4px;
  // }

  // .title-fix {
  //   margin: 0 0 12px 0;
  //   font-size: 14;
  // }
  // :deep(.section-title) {
  //   margin: 0 0 12px 0;
  //   font-size: 14px;
  // }
</style>
